<?php
/**
 * Post.php
 *
 * @category   Madoqua
 * @package    Module
 * @subpackage Blog
 */

/** Madoqua db table abstract */
require_once 'Madoqua/Db/Table/Abstract.php';

/** intersection table */
require_once 'PostCategory.php';

/** blog comments */
require_once 'Comment.php';

/** row class */
require_once 'Post/Row.php';

/** url model */
require_once 'Url.php';

/**
 * Blog_Post
 *
 * posts model
 *
 * @category   Madoqua
 * @package    Module
 * @subpackage Blog
 */
class Blog_Post extends Madoqua_Db_Table_Abstract {

    /**
     * row class
     *
     * @var string
     */
    protected $_rowClass = 'Blog_Post_Row';

    /**
     * table name
     *
     * @var string
     */
    protected $_name = 'post';

    /**
     * Primary column/columns
     *
     * @var string
     */
    protected $_primary = 'id';    
    
    /**
     * tables that depend on this one
     *
     * @var array
     */
    protected $_dependentTables = array('Blog_PostCategory', 'Blog_Comment');

    /**
     * generate a slug for a given string
     *
     * @param string $string
     * @param bool $checkExists check for existing slug and add numbers to slug
     * @return string
     */
    public static function slugify($string, $checkExists = false) {

        $string = Blog_Url::slugify($string);

        if ($checkExists) {
            $model = new Blog_Post();
            $slug = $string;
            $select = $model->select()->where('slug = ?', $slug);
            $x = 2;
            while($model->fetchRow($select) != null) {
                $slug = $string . $x++;
                $select = $model->select()->where('slug = ?', $slug);
            }
            //update if it already exists
            $string = $slug;
        }
        
        return $string;
    }
    
    /**
     * Inserts a new row.
     *
     * @param  array  $data  Column-value pairs.
     * @return mixed         The primary key of the row inserted.
     */
    public function insert(array $data)
    {
        if (empty($data['slug'])) {
            $data['slug'] = Blog_Post::slugify($data['title'], true);
        }
        //update slug if it doesn't exist
        
        return parent::insert($data);
    }
    
    /**
     * Delete a post
     *
     * @param int $id The id of the post to delete
     * @return bool True if a post was deleted, false otherwise
     */
	public function deleteById($id) 
	{
		return (boolean)$this->delete('id = ' . (int)$id);
	}

    /**
     * fetch a post by slug
     *
     * @param string $slug
     * @return Zend_Db_Table_Row
     */
    public function fetchBySlug($slug)
    {
        return $this->fetchRow($this->select()->where('slug = ?', $slug));
    }

    /**
     * fetch a post by id
     *
     * @param string $id
     * @return Zend_Db_Table_Row
     */
    public function fetchById($id)
    {
        return $this->fetchRow($this->select()->where('id = ?', $id));
    }

    /**
     * fetch a post by timespan
     *
     * @param string $start
     * @param string $end
     * @param int $count
     * @return Zend_Db_Table_RowSet
     */
    public function fetchByTimeSpan($start, $end, $count = null)
    {
        return $this->fetchAll(
                $this->select()->where('posted > ?', $start)
                ->where('posted < ?', $end)
            , null, $count);
    }

    /**
     * fetch the single latest post
     *
     * @return Zend_Db_Table_Row
     */
    public function fetchLatestPost()
    {
        return $this->fetchRow($this->select()->order('ID desc')
        ->limit(1));
    }

    /**
     * fetch previous posts for a given post
     *
     * @param Zend_Db_Table_Row $post
     * @param int $count
     * @return Zend_Db_Table_Rowset
     */
    public function fetchPreviousPosts($post, $count = 1)
    {
        return $this->fetchAll($this->select()->where('id < ?', $post->id)
        ->order('id DESC')
        ->limit($count));
        //select the previous row (if any)
    }

    /**
     * fetch next posts from a given post
     *
     * @param Zend_Db_Table_Row $post
     * @param int $count
     * @return Zend_Db_Table_Rowset
     */
    public function fetchNextPosts($post, $count = 1)
    {
        return $this->fetchAll($this->select()->where('id > ?', $post->id)
        ->order('id ASC')
        ->limit($count));
        //select the next rows (if any)
    }

    /**
     * get intro from complete text
     *
     * @param string $content
     * @todo create optional intro field?
     */
    public static function getIntro($content) {
        return substr($content, 0, 10000);
    }

    /**
     * search for a set of blog posts
     *
     * @param string $q
     * @return array Zend_Search_Lucene_Search_QueryHit
     */
    public static function search($q) {
        $indexer = Madoqua_Search_Indexer::getIndexer();
        $query = new Zend_Search_Lucene_Search_Query_Boolean();
        //we're building a query... a query, lalalala!

        $userQuery = Zend_Search_Lucene_Search_QueryParser::parse($q);
        $query->addSubquery($userQuery, true);
        //add the user part

        $postTerm  = new Zend_Search_Lucene_Index_Term('blog_post', 'type');
        $query->addSubquery(new Zend_Search_Lucene_Search_Query_Term($postTerm), true);
        //make sure we're looking for posts
        
        return $indexer->find($query);
    }
}